<?php

namespace App\Api\Controller;

use App\Api\Requests\UserRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use EasyWeChat\Factory;
use App\Models\User;

class AuthController extends BaseController
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login','verifyCode']]);
    }

    /**
     * Get a JWT token via given credentials.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $userInfo = $request->post('userInfo');
        $code = $request->post('code');

        if (empty($code)) {
            return $this->sendData([],'参数错误',400);
        }

        //将 临时code 发送到微信接口服务器换取微信用户信息：openid等
        $config = [
            'app_id' => 'wx32e654f209d03f7a',
            'secret' => 'fdb568f185eda66a2bbf3bd72240fdcc',
        ];
        $app = Factory::miniProgram($config);

        $wxData = $app->auth->session($code);

        if (empty($wxData['openid']) || empty($wxData['session_key'])) {
            return $this->sendData($wxData,'获取用户失败',400);
        }
        $user = User::query()->where('wx_openid','=',$wxData['openid'])->first();

        if (empty($user)) {
            $user = new User();
            $user->wx_openid = $wxData['openid'];
            $user->wx_session_key = $wxData['session_key'];
            $user->avatar = $userInfo['avatarUrl'] ?? '';
            $user->gender = (int)$userInfo['gender'] ?? '';
            $user->country = $userInfo['country'] ?? '';
            $user->province = $userInfo['province'] ?? '';
            $user->language = $userInfo['language'] ?? '';
            $user->city = $userInfo['city'] ?? '';
            $user->name = $userInfo['nickName'] ?? '';
            $user->save();
        }

        if ($token = Auth::login($user)) {
            return $this->sendData(['token' => $token],'登录成功');
        }

        return $this->sendData([],'微信授权登录失败', 401);
    }

    /**
     * Get the authenticated User
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json($this->guard()->user());
    }

    /**
     * Log the user out (Invalidate the token)
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $this->guard()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken($this->guard()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $this->guard()->factory()->getTTL() * 60
        ]);
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\Guard
     */
    public function guard()
    {
        return Auth::guard();
    }
}
